<?php
/*
included in wp-formazione plugin 
This file allow to create new post type modulo
Version: 1.0
Author: Carmine Ricco - Luca De Cristofano
Author URI: #
License: GPL2
*/

$pluginDir = basename(dirname(__FILE__));
$pluginPath	= WP_PLUGIN_DIR . '/' . $pluginDir;

require_once($pluginPath . "/wp-formazione_includes.php");	



wpf_modulo_hooks();

// fissa gli hook
function wpf_modulo_hooks() {
    // creo il plugin ed i relativi menu
    register_activation_hook(__FILE__, 'wpf_modulo_rewrite_flush');  // serve per i permalink
    add_action('init', 'wpf_modulo_init'); // quando inizializzo la pagina
    
    
    // genero la tabella per la visualizzazione dei moduli :

    add_filter('manage_edit-wpf_modulo_columns','wpf_modulo_list_column_header'); // aggiunge la colonna "azienda" alla lista dei fascicoli
    add_action('manage_wpf_modulo_posts_custom_column',  'wpf_modulo_list_column_row', 10, 2 ); // riempie la colonna azienda alla lista dei fascicoli
    add_filter('manage_edit-wpf_modulo_sortable_columns', 'wpf_modulo_list_sort_columns' ); // rende ordinabile per una colonna
 
    add_filter('wpf_modulo_field', 'wpf_modulo_render_field', 10, 2);
    add_filter('wpf_progetto_available_statuses','wpf_modulo_filter_status');
    
    add_filter('save_post','wpf_modulo_save',50,2);
    add_action( 'save_post', 'wpf_modulo_statusflow',10,2 );
    
 }


// inizializza quello che serve
function wpf_modulo_init() {


        // creazione del posttype
	  $labels = array(
	    'name' => _x('Moduli', 'Raccolgono i contenuti del corso e delle schede di attivit?'),
	    'singular_name' => _x('Modulo', 'Nome singolare del modulo'),
	    'add_new' => _x('Aggiungi nuovo', 'wpf_modulo'),
	    'add_new_item' => __('Nuovo Modulo'),
	    'edit_item' => __('Modifica Modulo'),
	    'new_item' => __('Nuovo Modulo'),
	    'all_items' => __('Tutti i moduli'),
	    'view_item' => __('Visualizza questo modulo'),
	    'search_items' => __('Cerca un modulo'),
	    'not_found' =>  __('Nessun modulo trovato'),
	    'not_found_in_trash' => __('Non ci sono moduli nel cestino'), 
	    'parent_item_colon' => '',
	    'menu_name' => 'Moduli'
	  );


	$args = array(
	        'labels' => $labels,
                'public' => true,
                'publicly_queryable' => true,
                'show_ui' => true, 
                'show_in_menu' => true, 
                'query_var' => true,
                'rewrite' => array('slug' => 'modulo'),
                'capability_type' => array('modulo','moduli'),
                'map_meta_cap' => true,
                'has_archive' => true, 
                'hierarchical' => true,
                'menu_position' => null,
                'supports' => array('title'),
        );
          
	register_post_type('wpf_modulo',$args);			
	
        if (taxonomy_exists('argomento')) {
            // la tassonomia dovrebbe essere gi? stat creata dal progetto
            register_taxonomy_for_object_type('argomento', 'wpf_modulo');
        } else {
            // la creo io (ma c'? qualcosa che non va)
 	  $labels = array(
	    'name' => _x( 'Argomento', 'taxonomy general name' ),
	    'singular_name' => _x( 'Argomento', 'taxonomy singular name' ),
	    'search_items' =>  __( 'Cerca gli argomenti' ),
	    'all_items' => __( 'Tutti gli argomenti' ),
	    'parent_item' => __( 'Argomento superiore' ),
	    'parent_item_colon' => __( 'Argomento Superiore:' ),
	    'edit_item' => __( 'Modifica Argomento' ), 
	    'update_item' => __( 'Aggiorna Argomento' ),
	    'add_new_item' => __( 'Aggiungi Nuovo Argomento' ),
	    'new_item_name' => __( 'Nome Argomento' ),
	    'menu_name' => __( 'Argomento' ),
	  ); 	
          register_taxonomy('argomento', 'wpf_modulo', array(
	    'hierarchical' => true,
	    'labels' => $labels,
	    'show_ui' => true,
	    'query_var' => true,
	    'rewrite' => array( 'slug' => 'argomento' ),
	  ));
        }
 
        $val_prj = get_posts(wpf_get_query('progetti_approvati'));
        $values = '';
        foreach($val_prj as $id => $val ) $values .= $val->ID.':'.$val->post_title.',';
        $values = trim($values,',');

        $form_fields = array(
		'progetto' => array(
				 'type' => 'select',
				 'description'=>__("Project", WPF_DOMAIN ),
                                 'values' => $values,
				 'howto' => __("The project to associate the Module", WPF_DOMAIN ),
                                 //'default' => $post->post_parent //@FIXME ma qui ancora non ho ancora post!!!
				 )
	);

        //@TODO va controllato il "save" perchè devo aggiornare il post_parent
        register_post_box('wpf_modulo', 'parent', 'Progetto', 'core', 'high', $form_fields);
        
        
        $dispensing_values = __("Online", WPF_DOMAIN ).",".__("Offline", WPF_DOMAIN ).",".__("Class", WPF_DOMAIN );
        $admis_values = __("Always", WPF_DOMAIN ).",".__("If completed previous", WPF_DOMAIN ).",".__("If right level", WPF_DOMAIN ).",".__("After days", WPF_DOMAIN );
        $when_closed_values = __("Always", WPF_DOMAIN ).",".__("If completed previous", WPF_DOMAIN ).",".__("If right level", WPF_DOMAIN ).",".__("After days", WPF_DOMAIN );
        $when_completed_values = __("Always", WPF_DOMAIN ).",".__("If completed previous", WPF_DOMAIN ).",".__("If right level", WPF_DOMAIN ).",".__("After days", WPF_DOMAIN );
   
        $form_fields = array(
            'hour' => array(
                'type' => 'littlenumber', 
                'description' => __("Estimated hours", WPF_DOMAIN ), 
                'howto' => __("The estimated hours for the duration of the module", WPF_DOMAIN )
            ),
            'program' => array(
                'type' => 'longtext', 
                'description' => __("Program", WPF_DOMAIN ), 
                'howto' => __("The program of the Module", WPF_DOMAIN )
            ),
            'evaluation_admission' => array(
                'type' => 'longtext', 
                'description' => __("Evaluation admission", WPF_DOMAIN ),
                'howto' => __("The procedure for evaluation admission", WPF_DOMAIN )
            ),
            'evaluation_understanding' => array(
                'type' => 'longtext', 
                'description' => __("Evaluation understanding", WPF_DOMAIN ), 
                'howto' => __("The procedure to evaluate understanding", WPF_DOMAIN )                
            ),
            'validation_mode' => array(
                'type' => 'longtext', 
                'description' => __("Validation mode", WPF_DOMAIN ), 
                'howto' => __("Procedure to validate this module", WPF_DOMAIN )
                
            ),
        );
        
        register_post_box('wpf_modulo', 'design_modulo', 'Progettazione del modulo', 'advanced', 'core', $form_fields);
        
        $form_fields = array(
            'dispensing' => array(
                'type' => 'select', 
                'description' => __("Dispensing", WPF_DOMAIN )."|".$dispensing_values, 
                'howto' => __("Type of dispensing", WPF_DOMAIN ), 
                
            ),
            'admission' => array(
                'type' => 'select&text', 
                'description' => __("Admission", WPF_DOMAIN ),
                'values' =>$admis_values,
                'closer' => 'days',
                'howto' => __("When an user is allowed to enter", WPF_DOMAIN ),
                'option' => 5 // ha anche admission_option
            ), 
            
            'when_close' => array(
                'type' => 'select&text', 
                'description' => __("When close", WPF_DOMAIN )."|".$when_closed_values."|"."days", 
                'howto' => __("Indicate when this module must be closed", WPF_DOMAIN ),
                'automation' => 'onselect="on_select_when_closed()"',
                'option' => 5  //ha anche when_close_option 
            ),
            'when_completed' => array(
                'type' => 'select', 
                'description' => __("When completed", WPF_DOMAIN )."|".$when_completed_values."|"."days", 
                'howto' => __("Indicate when this module must be considered completed", WPF_DOMAIN ),
                'option' => 5  //ha anche when_completed_option
            ),
        );
       
        
        register_post_box('wpf_modulo', 'config_modulo', 'Configurazione del modulo', 'advanced', 'low', $form_fields);
        
         
        $form_fields = array(
            'validation' => array(
                'type' => 'longtext', 
                'description' => __("Validation", WPF_DOMAIN ), 
                'howto' => __("Result of validation for this module", WPF_DOMAIN ) 
            ),
        );
        
        register_post_box('wpf_modulo', 'validation', 'Esito della validazione', 'advanced', 'low', $form_fields);
        
        
}

// serve per gestire i permalink
function wpf_modulo_rewrite_flush()
{
	wpf_modulo_init();
	flush_rewrite_rules();
}

function wpf_modulo_render_field($field, $field_id)
{
	global $post;
    if ($field_id == 'progetto')
	{
		$field['default']=$post->post_parent;
	}
	
	switch ($post->post_status)
	{
        case 'pending':
        case 'publish':
        case 'closed':
            if (in_array($field_id, array('hour', 'program', 'evaluation_admission', 'evaluation_understanding', 'validation_mode', 'dispensing', 'admission', 'when_close', 'when_completed')))
			{
				$field['readonly'] = true;
			}
        	break;
    }

    return $field;
}


// crea il box per BOXMODULO
function wpf_modulo_detail_box() {

    global $post;



  
  echo '<script type="text/javascript">
	
	jQuery(document).ready(function() {		
		if ( jQuery("#admission").val() == "After days" ) {
			jQuery("#days_admission").attr("readonly", false);
		} else {				
			jQuery("#days_admission").attr("readonly", true);
			jQuery("#days_admission").val("");
		}
		
		if ( jQuery("#when_closed").val() == "After days" ) {
			jQuery("#when_closed_opt").attr("readonly", false);
		} else {				
			jQuery("#when_closed_opt").attr("readonly", true);
			jQuery("#when_closed_opt").val("");
		}
		
		if ( jQuery("#when_completed").val() == "After days" ) {
			jQuery("#when_completed_opt").attr("readonly", false);
		} else {				
			jQuery("#when_completed_opt").attr("readonly", true);
			jQuery("#when_completed_opt").val("");
		}
	});	
	
    jQuery("#admission").change(function() {	       
        if ( jQuery(this).val() == "After days" ) {
			jQuery("#days_admission").attr("readonly", false);
			jQuery("#days_admission").val("'.$days_admis.'");
		} else {				
			jQuery("#days_admission").attr("readonly", true);
			jQuery("#days_admission").val("");
		}
    });	

    jQuery("#when_closed").change(function() {	       
        if ( jQuery(this).val() == "After days" ) {
			jQuery("#when_closed_opt").attr("readonly", false);
			jQuery("#when_closed_opt").val("'.$when_closed_opt.'");
		} else {				
			jQuery("#when_closed_opt").attr("readonly", true);
			jQuery("#when_closed_opt").val("");
		}
    });
	
	jQuery("#when_completed").change(function() {	       
        if ( jQuery(this).val() == "After days" ) {
			jQuery("#when_completed_opt").attr("readonly", false);
			jQuery("#when_completed_opt").val("'.$when_completed_opt.'");
		} else {				
			jQuery("#when_completed_opt").attr("readonly", true);
			jQuery("#when_completed_opt").val("");
		}
    });
	
  	
	</script>';
  
  
}




// aggiunge il contenuto della colonna nella tabella
function wpf_modulo_list_column_row( $column_name, $id ) {
global $post;
    // verifico quale colonna sto riempiendo
    if ( $column_name == 'status' )   echo $post->post_status;
    if ( $column_name == 'argomento' ) {
	        $argomento_terms = wp_get_object_terms($post->ID, 'argomento');
	        if(!empty($argomento_terms)){
	            if(!is_wp_error( $argomento_terms )){
	                foreach($argomento_terms as $term){
	                    echo '<a href="'.get_term_link($term->slug, 'argomento').'">'.$term->name.'</a>, '; 
	                }
	            }
	        }
	    }
    }

// aggiunge le colonne della tabella
function wpf_modulo_list_column_header( $cols ) {
    $newcols['cb'] = $cols['cb']; // <input type="checkbox"/>
    $newcols['title'] = 'Titolo';
    $newcols['argomento'] = 'argomento';
    
    foreach ($cols as $k => $v) $newcols[$k] = $v;
    return $newcols;
}

// indica che la colonna è ordinabile
function wpf_modulo_list_sort_columns($cols) {	
	$cols['progetto'] = 'progetto';  
	$cols['argomento'] = 'argomento'; 
	return $cols;
}

function wpf_modulo_save($post_id, $post) {

    if ($post->post_type != 'wpf_modulo')
	{
		return;
	}
   
    $new_post = array('ID' => $post_id, 'post_parent' => get_post_meta($post_id, 'progetto',true));
    
    remove_action('save_post', 'wpf_modulo_save',50,2);
    wp_update_post($new_post);
    add_action('save_post', 'wpf_modulo_save',50,2);
    
    
}

function wpf_modulo_statusflow($post_id, $post) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if ($post->post_type!='wpf_modulo') return;
    
    $new_post['ID']=$post_id;
    if (($_POST['original_post_status']=='draft') && ($_POST['post_status']=='publish') )
            $new_post['post_status']='pending';
    if (($_POST['original_post_status']=='pending') && ($_POST['post_status']=='publish') )
            $new_post['post_status']='approved';
    if (($_POST['original_post_status']=='approved') && ($_POST['post_status']=='publish') ) 
            $new_post['post_status']='publish';
    if (($_POST['original_post_status']=='publish') && ($_POST['post_status']=='publish') ) 
            $new_post['post_status']='closed';

    remove_action( 'save_post', 'wpf_modulo_statusflow' ); // to remove loop!!
    wp_update_post($new_post);
    add_action( 'save_post', 'wpf_modulo_statusflow' ); // to add filter for next save!!

}

function wpf_modulo_filter_status($statuses) {
	global $post;

    $new_statuses = array();

    $new_statuses['draft']      = $statuses['draft'];
    $new_statuses['pending']    = $statuses['pending'];
    $new_statuses['publish']    = $statuses['publish'];
    $new_statuses['closed']     = $statuses['closed'];

    return $new_statuses;
}

?>